import { useEffect, useState, useCallback } from 'react'
import { useCanvasStore } from '../store/canvasStore'
import './FloatingToolbar.css'

export default function FloatingToolbar() {
  const { canvas, selectedObjects, setSelectedObjects } = useCanvasStore()
  const [position, setPosition] = useState({ x: 0, y: 0 })
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    if (!canvas) return

    // 监听鼠标事件
    const handleMouseDown = (e: fabric.IEvent) => {
      if (!e.e) return
      
      // 如果点击的是图片，显示工具栏
      if (e.target && e.target.type === 'image') {
        updateToolbarPosition(e.target as fabric.Image)
        setVisible(true)
      } else {
        setVisible(false)
      }
    }

    // 监听选择事件
    const handleSelection = (e: fabric.IEvent) => {
      if (!e.e || !e.selected || e.selected.length === 0) {
        setVisible(false)
        return
      }
      
      // 获取所有选中的图片对象
      const selectedImages = e.selected.filter(obj => obj.type === 'image') as fabric.Image[]
      if (selectedImages.length === 0) {
        setVisible(false)
        return
      }

      // 计算所有选中图片的边界框
      const boundingRect = canvas.getObjects()
        .filter(obj => selectedImages.includes(obj as fabric.Image))
        .reduce((rect, obj) => {
          const objRect = obj.getBoundingRect()
          return {
            left: Math.min(rect.left, objRect.left),
            top: Math.min(rect.top, objRect.top),
            right: Math.max(rect.right, objRect.left + objRect.width),
            bottom: Math.max(rect.bottom, objRect.top + objRect.height),
            width: Math.max(rect.right, objRect.left + objRect.width) - Math.min(rect.left, objRect.left),
            height: Math.max(rect.bottom, objRect.top + objRect.height) - Math.min(rect.top, objRect.top)
          }
        }, {
          left: Infinity,
          top: Infinity,
          right: -Infinity,
          bottom: -Infinity,
          width: 0,
          height: 0
        })

      // 计算边界框在画布中的位置
      const zoom = canvas.getZoom()
      const panX = canvas.viewportTransform![4]
      const panY = canvas.viewportTransform![5]

      // 打印框选区域信息
      console.log('框选区域信息:', {
        画布坐标系: {
          左上角坐标: `(${Math.round(boundingRect.left)}, ${Math.round(boundingRect.top)})`,
          右下角坐标: `(${Math.round(boundingRect.right)}, ${Math.round(boundingRect.bottom)})`,
          宽度: Math.round(boundingRect.width),
          高度: Math.round(boundingRect.height)
        },
        视口坐标系: {
          左上角坐标: `(${Math.round(boundingRect.left * zoom + panX)}, ${Math.round(boundingRect.top * zoom + panY)})`,
          右下角坐标: `(${Math.round(boundingRect.right * zoom + panX)}, ${Math.round(boundingRect.bottom * zoom + panY)})`,
          宽度: Math.round(boundingRect.width * zoom),
          高度: Math.round(boundingRect.height * zoom)
        },
        视口变换: {
          缩放比例: zoom.toFixed(2),
          平移: `(${Math.round(panX)}, ${Math.round(panY)})`
        },
        选中图片数量: selectedImages.length
      })

      // 计算工具栏在视口坐标系中的位置
      const toolbarX = boundingRect.left * zoom + panX + (boundingRect.width * zoom) / 2 // 水平居中
      const toolbarY = boundingRect.top * zoom + panY + boundingRect.height * zoom + 10 // 在边界框下方 10px
      
      setPosition({
        x: toolbarX,
        y: toolbarY
      })
      setVisible(true)
    }

    // 监听画布点击事件
    const handleCanvasClick = (e: fabric.IEvent) => {
      if (!e.e) return
      
      // 如果点击的是画布空白处，隐藏工具栏
      if (!e.target) {
        setVisible(false)
      }
    }

    // 监听画布缩放和平移事件
    const handleCanvasTransform = () => {
      if (!visible) return
      
      const activeObjects = canvas.getActiveObjects() as fabric.Image[]
      if (!activeObjects || activeObjects.length === 0) return

      // 计算所有选中图片的边界框
      const boundingRect = activeObjects.reduce((rect, obj) => {
        const objRect = obj.getBoundingRect()
        return {
          left: Math.min(rect.left, objRect.left),
          top: Math.min(rect.top, objRect.top),
          right: Math.max(rect.right, objRect.left + objRect.width),
          bottom: Math.max(rect.bottom, objRect.top + objRect.height),
          width: Math.max(rect.right, objRect.left + objRect.width) - Math.min(rect.left, objRect.left),
          height: Math.max(rect.bottom, objRect.top + objRect.height) - Math.min(rect.top, objRect.top)
        }
      }, {
        left: Infinity,
        top: Infinity,
        right: -Infinity,
        bottom: -Infinity,
        width: 0,
        height: 0
      })

      // 计算边界框在画布中的位置
      const zoom = canvas.getZoom()
      const panX = canvas.viewportTransform![4]
      const panY = canvas.viewportTransform![5]

      // 计算工具栏在视口坐标系中的位置
      const toolbarX = boundingRect.left * zoom + panX + (boundingRect.width * zoom) / 2 // 水平居中
      const toolbarY = boundingRect.top * zoom + panY + boundingRect.height * zoom + 10 // 在边界框下方 10px
      
      setPosition({
        x: toolbarX,
        y: toolbarY
      })
    }

    // 辅助函数：更新工具栏位置
    const updateToolbarPosition = (target: fabric.Image) => {
      const boundingRect = target.getBoundingRect()
      
      // 计算边界框在画布中的位置
      const zoom = canvas.getZoom()
      const panX = canvas.viewportTransform![4]
      const panY = canvas.viewportTransform![5]

      // 计算工具栏在视口坐标系中的位置
      const toolbarX = boundingRect.left * zoom + panX + (boundingRect.width * zoom) / 2 // 水平居中
      const toolbarY = boundingRect.top * zoom + panY + boundingRect.height * zoom + 10 // 在边界框下方 10px
      
      setPosition({
        x: toolbarX,
        y: toolbarY
      })
    }

    // 添加事件监听
    canvas.on('mouse:down', handleMouseDown)
    canvas.on('selection:created', handleSelection)
    canvas.on('selection:updated', handleSelection)
    canvas.on('selection:cleared', () => setVisible(false))
    canvas.on('mouse:down', handleCanvasClick)
    canvas.on('zoom:changed', handleCanvasTransform)
    canvas.on('pan:changed', handleCanvasTransform)

    return () => {
      canvas.off('mouse:down', handleMouseDown)
      canvas.off('selection:created', handleSelection)
      canvas.off('selection:updated', handleSelection)
      canvas.off('selection:cleared', () => setVisible(false))
      canvas.off('mouse:down', handleCanvasClick)
      canvas.off('zoom:changed', handleCanvasTransform)
      canvas.off('pan:changed', handleCanvasTransform)
    }
  }, [canvas, visible])

  // 处理删除
  const handleDelete = useCallback(() => {
    if (!canvas) return

    // 获取当前选中的对象
    const activeObjects = canvas.getActiveObjects()
    if (!activeObjects || activeObjects.length === 0) return

    // 删除所有选中的对象
    activeObjects.forEach(obj => {
      canvas.remove(obj)
    })

    // 清除选择状态
    canvas.discardActiveObject()
    canvas.requestRenderAll()

    // 更新状态
    setSelectedObjects([])
    setVisible(false)
  }, [canvas, setSelectedObjects])

  // 添加键盘事件监听
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.key === 'Delete' || e.key === 'Backspace') && canvas && canvas.getActiveObjects().length > 0) {
        e.preventDefault()
        handleDelete()
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => {
      window.removeEventListener('keydown', handleKeyDown)
    }
  }, [handleDelete, canvas])

  if (!visible) return null

  return (
    <div 
      className={`floating-toolbar ${visible ? 'visible' : ''}`}
      style={{
        left: `${position.x}px`,
        top: `${position.y}px`,
        transform: 'translateX(-50%)'
      }}
    >
      <button 
        onClick={handleDelete} 
        title="删除 (Delete)"
        className="delete-button"
      >
        <span className="icon">🗑️</span>
      </button>
    </div>
  )
} 